import * as step from '@flow-step/step-toolkit'
import process from 'process'
import * as script from './script'

const ENV_GIVEN_EXEC_SHELL: string = 'GIVEN_EXEC_SHELL'
const ENV_IF_GIVEN_SHELL: string = 'IF_GIVEN_SHELL'



async function runStep(): Promise<void> {
    // 运行用户命令

    // 判断环境变量PIPELINE_LOCALE，如果值为zh_CN则设置LANG环境变量
    const pipelineLocale: string | undefined = process.env['PIPELINE_LOCALE']
    if (pipelineLocale && pipelineLocale === 'zh_CN') {
        step.exportEnvVar('LANG', 'zh_CN.UTF-8')
        step.info('Set LANG=zh_CN.UTF-8 based on PIPELINE_LOCALE=zh_CN')
    }

    const inputShell: string | undefined = process.env[ENV_GIVEN_EXEC_SHELL]
    const useGivenShell: string | undefined =  process.env[ENV_IF_GIVEN_SHELL]

    step.info(`Given shell executor: [${inputShell}] useGivenShell: [${useGivenShell}]`)
    let execShell = inputShell
    if (!execShell || "true" != useGivenShell ) {
        execShell = script.getDefaultShell()
    }
    step.info(`Invoke script with shell [${execShell}]`)
    const exitCode = await script.runUserScript(execShell, getScriptFile())
    if (exitCode != 0) {
        throw new Error(`run user script failed, exit code: ${exitCode}`)
    }
}

function getScriptFile(): string {
    let stepArgs = process.argv.slice(2)
    if (stepArgs.length == 0) {
        throw new Error('missing step shell script')
    }
    return stepArgs[0] as string
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
